package com.zhangzhan.runner;

import com.zhangzhan.domain.commcon.App;
import com.zhangzhan.domain.entity.Article;
import com.zhangzhan.mapper.ArticleMapper;
import com.zhangzhan.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 启动时执行
 * @date 2022/12/4 21:18
 */
@Component
@Slf4j
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    RedisCache redisCache;

    /**
     * @param args
     * @return void
     * @description 博客浏览量从数据库更新到redis
     * @author 31115
     * @date 2022/12/4 21:19
     */
    @Override
    public void run(String... args) throws Exception {
        //先从数据库中查出所有的博客id和浏览量
        List<Article> articles = articleMapper.selectList(null);
        //需要存入redis的hash结果中，把查出来的数据转成map集合
        Map<String, Integer> articleMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article -> article.getViewCount().intValue()));

        //存入redis
        redisCache.setCacheMap(App.ARTICLE_VIEWCOUNT,articleMap);

    }
}
